package by.onlinernews.newsfull;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.widget.TextView;
import by.onlinernews.newslist.MainActivity;

public class URLImageParser implements ImageGetter {
	Context c;
	TextView container;
	private Map<String, URLDrawable> drawableList;
	ExecutorService imageLoader;
	Activity a;

	/***
	 * Construct the URLImageParser which will execute AsyncTask and refresh the
	 * container
	 * 
	 * @param t
	 * @param c
	 */
	public URLImageParser(TextView t, Context c, Activity a) {
		Log.d("drawable", "new URLImageParser ");
		this.c = c;
		this.container = t;
		this.a = a;
		drawableList = new HashMap<String, URLDrawable>();
		imageLoader = Executors.newFixedThreadPool(1);

	}

	public Drawable getDrawable(String source) {
		URLDrawable urlDrawable = new URLDrawable();

		// get the actual source

		Log.d("drawable", "getDrawable: " + source);
		drawableList.put(source, urlDrawable);
		loadImage run = new loadImage(source);
		imageLoader.execute(run);

		Log.d("drawable", "return drawable");
		// return reference to URLDrawable where I will change with actual image
		// from
		// the src tag
		return urlDrawable;
	}

	public class loadImage implements Runnable {
		String source;

		public loadImage(String source) {
			this.source = source;

		}

		@Override
		public void run() {
			try {
				Log.d("drawable", "load Drawable : " + source);
				BitmapFactory.Options o = new BitmapFactory.Options();
				o.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(
						(InputStream) new URL(source).getContent(), null, o);
				final int REQUIRED_SIZE = 200;
				int scale = 1;
				while (o.outWidth / scale / 2 >= REQUIRED_SIZE
						&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
					scale *= 2;
				BitmapFactory.Options o2 = new BitmapFactory.Options();
				o2.inSampleSize = scale;
				Bitmap bitmap;
				bitmap = BitmapFactory.decodeStream((InputStream) new URL(
						source).getContent(), null, o2);
				Drawable drawable = new BitmapDrawable(null, bitmap);
				//int higth = drawable.getIntrinsicHeight() * MainActivity.width
			//			/ drawable.getIntrinsicWidth();
				Log.d("drawable",
						"Bounds: right: " + drawable.getIntrinsicWidth()
								+ " bottom: " + drawable.getIntrinsicHeight());
				//drawable.setBounds(0, 0, 0 + MainActivity.width, 0 + higth);

				refreshTextView refresh = new refreshTextView(source, drawable);
				a.runOnUiThread(refresh);
			} catch (IOException e) {
				e.printStackTrace();
			}

		}

	}

	public class refreshTextView implements Runnable {
		String source;
		Drawable result;

		public refreshTextView(String source, Drawable result) {
			this.result = result;
			this.source = source;

		}

		@Override
		public void run() {
			URLDrawable urlDrawable = drawableList.get(source);
			Log.d("drawable", "height " + result.getIntrinsicHeight());
			Log.d("drawable", "width " + result.getIntrinsicWidth());
			Log.d("drawable", "update view: ");
			//int higth = result.getIntrinsicHeight() * MainActivity.width
			//		/ result.getIntrinsicWidth();
			Log.d("drawable", "get URLDrawable");
			Log.d("drawable", "set bounds");
			//urlDrawable.setBounds(0, 0, 0 + MainActivity.width, 0 + higth);

			// change the reference of the current drawable to the result
			// from the HTTP call
			urlDrawable.drawable = result;
			Log.d("drawable", "invalidate container " + (container != null));
			// redraw the image by invalidating the container
			URLImageParser.this.container.invalidate();
			Log.d("drawable", "set Heigth");
			// For ICS
			//URLImageParser.this.container
			//		.setHeight((URLImageParser.this.container.getHeight() + higth));

			// Pre ICS
			URLImageParser.this.container.setEllipsize(null);

		}
	}

	public class ImageGetterAsyncTask extends
			AsyncTask<String, String, Drawable> {
		URLDrawable urlDrawable;
		String source;

		public ImageGetterAsyncTask() {
		}

		@Override
		protected Drawable doInBackground(String... params) {

			source = params[0];
			Log.d("drawable", "begin download " + source);
			if (source.indexOf("play.jpg") != -1) {
				try {
					Log.d("drawable", "get file from assets ");
					return Drawable.createFromStream(
							c.getAssets().open("play.jpg"), null);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			return fetchDrawable(source);
		}

		@Override
		protected void onPostExecute(Drawable result) {
			// set the correct bound according to the result from HTTP call
			if (result == null)
				return;
			Log.d("drawable", "height " + result.getIntrinsicHeight());
			Log.d("drawable", "width " + result.getIntrinsicWidth());
			Log.d("drawable", "update view: ");
			//int higth = result.getIntrinsicHeight() * MainActivity.width
			//		/ result.getIntrinsicWidth();
			Log.d("drawable", "get URLDrawable");
			urlDrawable = drawableList.get(source);
			Log.d("drawable", "set bounds");
		//	urlDrawable.setBounds(0, 0, 0 + MainActivity.width, 0 + higth);

			// change the reference of the current drawable to the result
			// from the HTTP call
			urlDrawable.drawable = result;
			Log.d("drawable", "invalidate container " + (container != null));
			// redraw the image by invalidating the container
			URLImageParser.this.container.invalidate();
			Log.d("drawable", "set Heigth");
			// For ICS
			//URLImageParser.this.container
			//		.setHeight((URLImageParser.this.container.getHeight() + higth));

			// Pre ICS
			URLImageParser.this.container.setEllipsize(null);
		}

		/***
		 * Get the Drawable from URL
		 * 
		 * @param urlString
		 * @return
		 */
		public Drawable fetchDrawable(String urlString) {
			Bitmap bitmap;
			try {
				// InputStream is = fetch(urlString);
				Log.d("drawable", "load Drawable : " + urlString);
				BitmapFactory.Options o = new BitmapFactory.Options();
				o.inJustDecodeBounds = true;
				BitmapFactory.decodeStream(
						(InputStream) new URL(urlString).getContent(), null, o);
				// The new size we want to scale to
				final int REQUIRED_SIZE = 200;

				// Find the correct scale value. It should be the power of 2.
				int scale = 1;
				while (o.outWidth / scale / 2 >= REQUIRED_SIZE
						&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
					scale *= 2;

				// Decode with inSampleSize
				BitmapFactory.Options o2 = new BitmapFactory.Options();
				o2.inSampleSize = scale;
				// HKEY_CURRENT_USER\Software\Google\Chrome\Metro
				bitmap = BitmapFactory.decodeStream((InputStream) new URL(
						urlString).getContent(), null, o2);
				Drawable drawable = new BitmapDrawable(null, bitmap);
				//int higth = drawable.getIntrinsicHeight() * MainActivity.width
				//		/ drawable.getIntrinsicWidth();
				Log.d("drawable",
						"Bounds: right: " + drawable.getIntrinsicWidth()
								+ " bottom: " + drawable.getIntrinsicHeight());
				//drawable.setBounds(0, 0, 0 + MainActivity.width, 0 + higth);
				return drawable;
			} catch (Exception e) {
				return null;
			}
		}

		public InputStream fetch(String urlString)
				throws MalformedURLException, IOException {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(urlString);
			HttpResponse response = httpClient.execute(request);
			return response.getEntity().getContent();
		}
	}
}
